import random
import cv2
from PIL import Image, ImageDraw, ImageFont
import os
import yaml
import numpy as np
############################
import logging
from django.db import transaction

my_normal_logger = logging.getLogger('django')
############################
from main_function.models import CameraInfo, CameraOffsetRecord

table_dict = {'CameraInfo': CameraInfo, 'CameraOffsetRecord': CameraOffsetRecord}


def parse_yaml(config_path):
    with open(config_path, 'r') as f:
        default_arg = yaml.load(f, Loader=yaml.FullLoader)

    return default_arg


def generate_name(num=11, many=1):
    for x in range(many):
        name = ""
        for i in range(num):
            n = random.randint(1, 2)
            if n == 1:
                numb = random.randint(0, 9)
                name += str(numb)
            else:
                nn = random.randint(1, 2)
                cc = random.randint(1, 26)
                if nn == 1:
                    numb = chr(64 + cc)
                    name += numb
                else:
                    numb = chr(96 + cc)
                    name += numb
        return name


# 摄像机角度偏移告警
def putText(frame, text):
    cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    pil_im = Image.fromarray(cv2_im)

    draw = ImageDraw.Draw(pil_im)
    # font = ImageFont.truetype("fonts/msyh.ttc", 30, encoding="utf-8")
    font = ImageFont.truetype("fonts/msjh.ttc", 50, encoding="utf-8")
    draw.text((50, 50), text, (255, 0, 255), font=font)

    cv2_text_im = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)

    return cv2_text_im


def show_frame(frame):
    cv2.namedWindow("camera", 0)
    while True:
        cv2.imshow("camera", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()


def save_pic(frame, save_path):
    my_normal_logger.info('Save Picture Path:' + save_path)
    if not os.path.exists(os.path.dirname(save_path)):
        os.makedirs(os.path.dirname(save_path))
    cv2.imwrite(save_path, frame)
    my_normal_logger.info('Succeed Save Picture')


# 装饰器为启用mysql事务 否则无法插入数据
@transaction.atomic
def change_db(table_name, operation_type, **kwargs):
    """
    CameraInfo(ip="", region="", ip_is_work="", ip_is_sensitive="")
    CameraOffsetRecord(ip="", offset_pic_path="", offset_date="", reset_date="")
    kwargs传入key必须与表字段名保持一致
    """
    if operation_type == 'creat':
        # 插入数据
        if table_dict[table_name].objects.filter(ip=kwargs['ip']).last().reset_date:
            # 如果最后的一条记录中摄像头没有回正日期则不在新增该摄像头的偏移记录
            obj = table_dict[table_name](**kwargs)
            obj.save()
        else:
            pass
    elif operation_type == 'update':
        # 修改数据
        obj = table_dict[table_name].objects.filter(ip=kwargs['ip']).last()
        if obj:
            if table_name == 'CameraOffsetRecord':
                obj.reset_date = kwargs['reset_date']
            elif table_name == 'CameraInfo':
                obj.ip_is_work = kwargs['ip_is_work']
            obj.save()
